package com.leaf.spring.y201906.day12.websocket;

import java.security.Principal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;

@Controller
public class GreetingController {
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	// @MessageMapping和@RequestMapping功能类似，用于设置URL映射地址，浏览器向服务器发起请求，需要通过该地址。
	@MessageMapping("/hello")
	// 如果服务器接受到了消息，就会对订阅了@SendTo括号中的地址传送消息。
	@SendTo("/topic/greetings")
	public Greeting greeting(HelloMessage message) {
		return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
	}

	@Autowired
	private SimpMessagingTemplate messagingTemplate;

	@MessageMapping("/chat")
	public void handleChat(Principal principal, String msg) {
		
		logger.info("===> {} : {}", principal.getName(), msg);
		
		if (principal.getName().equals("leaf")) {// 3
			messagingTemplate.convertAndSendToUser("tsing", "/queue/notifications",
					principal.getName() + "-send:" + msg);
		} else {
			messagingTemplate.convertAndSendToUser("leaf", "/queue/notifications",
					principal.getName() + "-send:" + msg);
		}
	}

}
